package helixoide;

/**
 * Utilities log
 */
import java.io.*;
import java.text.*;
import java.util.*;

public class hxLog 
{
	private static int logCount;//variable to hold the current amount of messages in the log
	private static int logLength = 100;//this means 100 messages, not 100 lines
    private static String logFile = "/slirc.log";
    private final static DateFormat df = new SimpleDateFormat ("yyyy.MM.dd  hh:mm:ss ");
    public static void setLogFilename(String filename) 
    {
        logFile = filename;
        new File(filename).delete();

        try 
        {
            write("LOG file : " + filename);
        }
        catch (Exception e) 
        { 
            System.out.println(stack2string(e));
        }
        
    }
    
    public static void write(String msg) 
    {
        write(logFile, msg);
    }
    
    public static void write(Exception e) 
    {
        write(logFile, stack2string(e));
    }
    private static void clear(String logfile)
    {
    	try
    	{
    		FileOutputStream erasor = new FileOutputStream(logfile);
    		String clear = new String();
    		erasor.write(clear.getBytes());
    		erasor.close();
    	}
    	catch(Exception e)
    	{
    		System.out.println(stack2string(e));
    	}
    }
    public static void write(String file, String title, String msg)
    {
    	try
    	{
    		Date now = new Date();
    		String currentTime = hxLog.df.format(now); 
    		FileWriter aWriter = new FileWriter(file, true);
    		aWriter.write(currentTime + ": " + title + ": " + msg 
                + System.getProperty("line.separator"));
    		System.out.println(currentTime + " " + msg);
    		aWriter.flush();
    		aWriter.close();
    	}
    	catch (Exception e) 
        {
            System.out.println(stack2string(e));
        }
    }
    public static void write(String title, String msg) 
    {
    	if(logCount>=logLength)
    	{
    		hxLog.clear(hxLog.logFile);
    		logCount = 0;
    	}
        try 
        {
            Date now = new Date();
            String currentTime = hxLog.df.format(now); 
            FileWriter aWriter = new FileWriter(logFile, true);
            aWriter.write(currentTime + ": " + title + ": " + msg 
                    + System.getProperty("line.separator"));
            System.out.println(currentTime + " " + msg);
            aWriter.flush();
            aWriter.close();
            logCount++;
        }
        catch (Exception e) 
        {
            System.out.println(stack2string(e));
        }
    }
    
    private static String stack2string(Exception e) 
    {
        try 
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "------\r\n" + sw.toString() + "------\r\n";
        }
        catch(Exception e2) 
        {
            return "bad stack2string";
        }
    }
}
